App({

  // 小程序初始化
  onLaunch: function () {

    // 检查登录态
    this.checkSession();

    // 缓存用户信息
    this.getUserInfo();
  },

  // 检查登录态
  checkSession: function () {
    var that = this;
    wx.checkSession({

      // 有效
      success: function () {
        //（检测有效且有3rd_session的storage，直接拿，不再请求接口）
        that.getLoginSession(function (res) {
          console.log('本地存储3rd_session为：' + res.data);
        })
      },

      // 失效
      fail: function () {
        that.login();
      }
    })
  },

  // 获取localStorage中的3rd_session，需要登录授权的接口使用
  getLoginSession: function (fn) {
    var that = this;
    wx.getStorage({
      key: 't_session',
      success: function (res) {

        // 有直接执行回调
        typeof fn == 'function' && fn(res.data);
        console.log('从localStorage中拿');
      },
      fail: function () {

        // 没有再次登录拿3rd_session
        that.login(function (res) {
          typeof fn == 'function' && fn(res);
          console.log('从登录接口拿');
        })
      }
    })
  },

  // 用户登录
  login: function (fn) {
    var that = this;
    wx.login({
      success: function (res) {

        console.log('本地登录成功');
        console.log(res);
        if (res.code) {
          wx.request({
            url: that.api,
            data: {
              app: 'oauth',
              act: 'wxlogin',
              code: res.code
            },
            success: function (result) {
              console.log(result);
              var session = result.data.retval.t_session;

              // 存储3rd_session
              wx.setStorage({
                key: "t_session",
                data: session,
                success: function () {
                  console.log('存储session成功');
                  typeof fn == 'function' && fn(session);
                },
                fail: function () {
                  console.log('存储session失败');
                }
              })
            }
          })

        } else {
          wx.showModal({
            title: '提示',
            content: '获取用户登录态失败！是否重新获取？',
            cancelText: '否',
            confirmText: '是',
            success: function (res) {
              if (res.confirm) {
                that.login();
              }
            }
          })
        }
      },
      fail: function () {
        console.log('本地登录失败');
      }
    });

  },

  // 获取用户信息
  getUserInfo: function (fn) {
    var that = this
    if (that.userInfo) {
      that.updateUserInfo(that.userInfo);
      typeof fn == "function" && fn(that.userInfo)
    } else {
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.updateUserInfo(res);
              typeof fn == "function" && fn(res);
            }
          })
        }
      })
    }
  },

  // 提交用户信息
  updateUserInfo: function (info) {
    var that = this;
    if (info) {
      console.log(info);
      that.getLoginSession(function (session) {
        wx.request({
          url: that.api + '?app=oauth&act=getUserInfo',
          data: {
            encryptedData: info.encryptedData,
            iv: info.iv,
            t_session: session
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          method: 'POST',
          success: function (result) {
            console.log(result.data);
          }
        })
      });
    }
  },

  // 获取支付信息
  callToPay: function (orderId, amount, fn) {

    var that = this;

    if (isNaN(orderId)) {
      return
    }

    that.getLoginSession(function (session) {
      // 请求
      wx.request({

        // 请求地址
        url: that.api,

        // 请求参数
        data: {
          app: 'cashier',
          act: 'index',
          order_id: orderId,
          t_session: session
        },

        // 请求成功
        success: function (res) {
          var data = res.data;
          if (data.done && data.retval) {
            var result = data.retval;
            console.log(result);

            // 优惠券抵消为0时直接到成功页
            if (amount == 0 && result.isPay && result.isPay == 1) {
              wx.navigateTo({
                url: '/pages/paySuccess/paySuccess',
              })
              return
            }
            // 唤起支付功能
            wx.requestPayment({
              'timeStamp': result.timeStamp,
              'nonceStr': result.nonceStr,
              'package': result.package,
              'signType': 'MD5',
              'paySign': result.paySign,
              'success': function (res) {
                console.log(res);
                wx.navigateTo({
                  url: '/pages/paySuccess/paySuccess',
                })
              },
              'fail': function (res) {
                console.log(res);
                wx.showModal({
                  title: '提示',
                  showCancel: false,
                  content: '支付失败'
                })
              }
            });
          } else {
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: '获取支付信息失败'
            })
          }
        }
      })

    })
  },

  // 存储用户信息
  userInfo: null,

  // 连续重复登录次数
  reLoginNum: 3,

  // 统一错误提示
  errorTips: '数据加载中...',

  // cdn静态文件地址(假装它是CDN)
  cdn: 'https://www.gzgaodu.com/static/',

  // 接口地址
  api: 'https://zp.gzgaodu.com/api/index.php'

});